<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import { searchPosts, batchUpdateHot, resetPostsHot } from '@/api/post/postHot'

// 查询条件
const queryForm = reactive({
  searchType: 'id', // id, title, author
  searchValue: '',
  timeRange: null
})

// 热度规则配置
const hotRules = reactive({
  maxHotValue: 1000,
  minHotValue: 0,
  defaultHotValue: 100,
  adjustmentStrategy: 'fixed', // fixed, percentage, gradual
  adjustmentValue: 100,
  gradualInterval: 30, // 分钟
  gradualStep: 10
})

// 预览数据
const previewPosts = ref([])
// 移除 showPreview 变量，因为我们始终显示预览区域
const selectedPosts = ref([])

// 统计信息
const statistics = computed(() => {
  if (!previewPosts.value.length) return null
  
  return {
    totalPosts: previewPosts.value.length,
    averageHot: Math.round(
      previewPosts.value.reduce((sum, post) => sum + post.hot, 0) / previewPosts.value.length
    ),
    maxHot: Math.max(...previewPosts.value.map(post => post.hot)),
    minHot: Math.min(...previewPosts.value.map(post => post.hot))
  }
})

// 搜索类型选项
const searchTypes = [
  { label: '帖子ID', value: 'id' },
  { label: '标题', value: 'title' },
  { label: '作者', value: 'author' }
]

// 热度调整策略选项
const strategyOptions = [
  { label: '固定值', value: 'fixed' },
  { label: '百分比', value: 'percentage' },
  { label: '渐进式', value: 'gradual' }
]

// 加载状态
const loading = ref(false)

// 获取帖子
const searchThePosts = async () => {
  if (!queryForm.searchValue && !queryForm.timeRange) {
    ElMessage.warning('请至少输入一个搜索条件')
    return
  }

  loading.value = true
  const loadingInstance = ElLoading.service({
    target: '.precise-flow',
    text: '搜索中...'
  })

  try {
    // 处理时间范围
    const [startTime, endTime] = queryForm.timeRange || [null, null]
    
    const params = {
      type: queryForm.searchType,
      value: queryForm.searchValue,
      startTime: startTime?.toISOString(),
      endTime: endTime?.toISOString()
    }

    const { data } = await searchPosts(params)
    previewPosts.value = data.map(post => ({
      ...post,
      originalHot: post.hot // 保存原始热度值
    }))
    ElMessage.success('搜索成功')
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败，请重试')
  } finally {
    loadingInstance.close()
    loading.value = false
  }
}

// 批量更新热度
const batchTheUpdateHot = async () => {
  if (!selectedPosts.value.length) {
    ElMessage.warning('请选择要操作的帖子')
    return
  }

  const loadingInstance = ElLoading.service({
    target: '.preview-section',
    text: '更新中...'
  })

  try {
    const updateData = {
      postIds: selectedPosts.value.map(post => post.id),
      strategy: hotRules.adjustmentStrategy,
      value: hotRules.adjustmentValue,
      gradualConfig: hotRules.adjustmentStrategy === 'gradual' ? {
        interval: hotRules.gradualInterval,
        step: hotRules.gradualStep
      } : undefined
    }

    await batchUpdateHot(updateData)
    ElMessage.success('热度更新成功')
    // 重新搜索以获取最新数据
    await searchThePosts()
  } catch (error) {
    console.error('更新失败:', error)
    ElMessage.error('热度更新失败，请重试')
  } finally {
    loadingInstance.close()
  }
}

// 重置所选帖子热度
const resetSelectedHot = async () => {
  if (!selectedPosts.value.length) {
    ElMessage.warning('请选择要操作的帖子')
    return
  }

  const loadingInstance = ElLoading.service({
    target: '.preview-section',
    text: '重置中...'
  })

  try {
    const postIds = selectedPosts.value.map(post => post.id)
    await resetPostsHot({ postIds })
    ElMessage.success('热度已重置')
    // 重新搜索以获取最新数据
    await searchThePosts()
  } catch (error) {
    console.error('重置失败:', error)
    ElMessage.error('热度重置失败，请重试')
  } finally {
    loadingInstance.close()
  }
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedPosts.value = selection
}
</script>

<template>
  <div class="precise-flow">
    <!-- 查询模块 -->
    <el-card class="search-section">
      <template #header>
        <div class="card-header">
          <span>查询条件</span>
        </div>
      </template>
      <el-form :model="queryForm" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="搜索类型">
              <el-select v-model="queryForm.searchType" class="w-full">
                <el-option
                  v-for="type in searchTypes"
                  :key="type.value"
                  :label="type.label"
                  :value="type.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="搜索内容">
              <el-input
                v-model="queryForm.searchValue"
                :placeholder="`请输入${searchTypes.find(t => t.value === queryForm.searchType)?.label}`"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="时间范围">
              <el-date-picker
                v-model="queryForm.timeRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                class="w-full"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button type="primary" @click="searchThePosts">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 热度规则配置 -->
    <el-card class="rules-section">
      <template #header>
        <div class="card-header">
          <span>热度规则配置</span>
        </div>
      </template>
      <el-form :model="hotRules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="最大热度值">
              <el-input-number v-model="hotRules.maxHotValue" :min="0" class="w-full" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="最小热度值">
              <el-input-number v-model="hotRules.minHotValue" :min="0" class="w-full" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="默认热度值">
              <el-input-number
                v-model="hotRules.defaultHotValue"
                :min="hotRules.minHotValue"
                :max="hotRules.maxHotValue"
                class="w-full"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="调整策略">
              <el-select v-model="hotRules.adjustmentStrategy" class="w-full">
                <el-option
                  v-for="strategy in strategyOptions"
                  :key="strategy.value"
                  :label="strategy.label"
                  :value="strategy.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="hotRules.adjustmentStrategy === 'percentage' ? '调整百分比' : '调整值'">
              <el-input-number
                v-model="hotRules.adjustmentValue"
                :min="0"
                :max="hotRules.adjustmentStrategy === 'percentage' ? 100 : hotRules.maxHotValue"
                class="w-full"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="hotRules.adjustmentStrategy === 'gradual'">
            <el-form-item label="递减间隔(分钟)">
              <el-input-number v-model="hotRules.gradualInterval" :min="1" class="w-full" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="hotRules.adjustmentStrategy === 'gradual'">
          <el-col :span="8">
            <el-form-item label="递减步长">
              <el-input-number v-model="hotRules.gradualStep" :min="1" class="w-full" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 预览结果 - 始终显示，不再使用v-if条件 -->
    <div class="preview-section">
      <el-card>
        <template #header>
          <div class="card-header">
            <div class="header-left">
              <span>预览结果</span>
              <el-tag v-if="statistics" type="info" class="ml-4">
                共 {{ statistics.totalPosts }} 条数据
              </el-tag>
              <el-tag v-else type="info" class="ml-4">暂无数据</el-tag>
            </div>
            <div class="header-right">
              <el-button type="primary" @click="batchTheUpdateHot" :disabled="!selectedPosts.length">
                批量更新热度
              </el-button>
              <el-button @click="resetSelectedHot" :disabled="!selectedPosts.length">
                重置热度
              </el-button>
            </div>
          </div>
        </template>

        <!-- 统计信息 -->
        <div v-if="statistics" class="statistics-info mb-4">
          <el-descriptions :column="3" border>
            <el-descriptions-item label="平均热度">
              {{ statistics.averageHot }}
            </el-descriptions-item>
            <el-descriptions-item label="最高热度">
              {{ statistics.maxHot }}
            </el-descriptions-item>
            <el-descriptions-item label="最低热度">
              {{ statistics.minHot }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
        
        <!-- 无数据提示 -->
        <el-empty v-if="!previewPosts.length" description="暂无数据，请进行搜索" />

        <!-- 数据表格 -->
        <el-table
          v-else
          :data="previewPosts"
          border
          @selection-change="handleSelectionChange"
          style="width: 100%"
          v-loading="loading"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="content" label="大致内容" show-overflow-tooltip />
          <el-table-column prop="topicId" label="话题ID" width="120" />
          <el-table-column prop="account" label="发布者账号" width="120" />
          <el-table-column prop="createTime" label="发布时间" width="180" />
          <el-table-column prop="weight" label="当前权重" width="180">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.weight"
                :min="hotRules.minHotValue"
                :max="hotRules.maxHotValue"
                class="w-full"
              />
            </template>
          </el-table-column>
          <el-table-column label="预计热度" width="120">
            <template #default="scope">
              <el-tag :type="scope.row.heat > hotRules.defaultHotValue ? 'danger' : 'success'">
                {{ (scope.row.heat * Math.log(scope.row.weight + 1)).toFixed(2) }} 
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<style scoped>
.precise-flow {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
}

.header-right {
  display: flex;
  gap: 12px;
}

.statistics-info {
  margin-top: 16px;
}

.w-full {
  width: 100%;
}

.ml-4 {
  margin-left: 16px;
}

.mb-4 {
  margin-bottom: 16px;
}
</style>